/* debug.c -- debug statements for ADVRP.
 *
 *    Copyright 2010 Patrick Allen
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
*/

#include <inttypes.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <sys/time.h>

#include "debug.h"

extern double START_TIME;

uint64_t DBG_FLAGS = 0;    /* No flags by default */
uint64_t DBG_LVL = ERR;    /* Only print error messages by default */
int MAX_DBG_PREFIX = 50;

/* Note: Use the DBG() macro instead of calling debug() directly. See debug.h */

void debug(const char * fn, uint64_t level, char * buf, ...)
{
	char msg[strlen(buf) + MAX_DBG_PREFIX];
	int plen = 0;    // Length of message prefix (not network prefix)

	/* If the debug level is not set to print this message, ignore it */
	if (! (DBG_LVL & level))
		return;

	/* Sort out message flags */
	if (DBG_FLAGS & TS_F) {
		struct timeval tv;
		double now;

		/* Prepend timestamp (time since program startup) */
		gettimeofday(&tv, NULL);
		now = tv.tv_sec + (tv.tv_usec / 1000000.0);
		plen += snprintf(&msg[plen], MAX_DBG_PREFIX - plen,
		                 "[%14.5lf] ", now - START_TIME);
	}

	if (DBG_FLAGS & FN_F) {
		/* Prepend calling function's name */
		plen += snprintf(&msg[plen], MAX_DBG_PREFIX - plen, "%s: ", fn);
	}

	/* Insert the buf argument */
	va_list arguments;
	va_start(arguments, buf);
	vsprintf(&msg[plen], buf, arguments);
	va_end(arguments);

	/* Print the message */
	fprintf(stderr, "%s\n", msg);

	return;
}
